package Net.tcp.chat4;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 接收端
 */
public class Receive implements Runnable {
    private Socket client;
    DataInputStream dis;
    boolean isRunning = true;
    public Receive(Socket client){
        this.client=client;
        try {
            dis= new DataInputStream(client.getInputStream());//getInputStream返回此套接字的输入流。
        } catch (IOException e) {
            release();
            e.printStackTrace();
        }
    }

    //释放资源
    private void release(){
        this.isRunning=false;
        Utils.close(dis,client);
    }

    @Override
    public void run() {
        while (isRunning){
            String msg = "";
            try {
                msg = dis.readUTF();
            } catch (IOException e) {
                release();
                e.printStackTrace();
            }
            if(!msg.equals("")){
                System.out.println(msg);
            }
        }
    }
}
